import random
from django.contrib.auth.models import User
from django.contrib import auth
from django.shortcuts import render, redirect, HttpResponse
import json, urllib
from urllib import parse, request


# 登陆
def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return redirect('home')
        else:
            return render(request, 'login.html', {"status": "登陆失败"})
    else:
        if request.user.id:
            return redirect("home")
        else:
            return render(request, "login.html")


# 退出登陆
def logout(request):
    if request.user.id:
        auth.logout(request)
    return redirect('home')


# 注册
def register(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        if User.objects.filter(username=username):
            return
        else:
            User.objects.create_user(username=username, password=password, first_name=username)
            user = auth.authenticate(username=username, password=password)
            auth.login(request, user)
            return redirect('home')
    else:
        if request.user.id:
            return redirect("home")
        else:
            return render(request, "register.html")


# 获取验证码
def getCode(request):
    # 验证码
    if request.method == 'POST':
        verification_code = str(random.randint(1000, 9999))
        phoneNum = request.POST.get("phoneNum")
        url = "http://v.juhe.cn/sms/send"
        params = {
            "mobile": phoneNum,  # 接受短信的用户手机号码
            "tpl_id": "148128",  # 您申请的短信模板ID，根据实际情况修改
            "tpl_value": '#code#=' + verification_code,  # 您设置的模板变量，根据实际情况修改
            "key": "bd267ab779d24d646d5072bc4d4dfc9b",  # 应用APPKEY(应用详细页查询)
        }
        params = urllib.parse.urlencode(params)
        f = urllib.request.Request(url + '?' + params)
        urllib.request.urlopen(f)
        # response = urllib.request.urlopen(f)
        # content = response.read()
        # res = json.loads(content)
        # if res:
        #     print(res)
        # else:
        #     print("请求异常")
        return HttpResponse(verification_code)


def index(request):
    return render(request, "index.html")
